package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter("/*") // 过滤所有请求
public class TokenFilter implements Filter {
    //过滤起初始化
    //初始化方法, web服务器启动, 创建Filter实例时调用, 只调用一次
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    //拦截到请求时,调用该方法,可以调用多次
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取url路径
      String url=  request.getRequestURI().toString();//     /login
        //如果是login请求，则放行
        if(url.contains("login"))
        {
            log.info("login请求放行");
            filterChain.doFilter(request,response);
            return;
        }
        //其他获取请求头的token
        String token= request.getHeader("token");
        //判断token是否存在 不存在返回401状态码
        if(token==null||token.equals(""))
        {
            log.error("token不存在");
            response.setStatus(401);
            return;
        }
        //存在判断token是否正确和是否过期
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("token解析成功, 放行");
        } catch (Exception e) {
            log.error("token验证失败");
            response.setStatus(401);
            return;
        }
        //如果正确，则放行
        log.info("token验证成功");
        filterChain.doFilter(request,response);

        //7. 清空当前线程绑定的id
        CurrentHolder.remove();
    }

    //销毁方法, web服务器关闭时调用, 只调用一次
    @Override
    public void destroy() {
        Filter.super.destroy();
    }





}
